package com.ybbase.framework.controller.system;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.base.model.ResponseBean;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.enums.LogFunType;
import com.ybbase.framework.common.enums.LogType;
import com.ybbase.framework.common.util.BeanUtil;
import com.ybbase.framework.common.util.DESUtil;
import com.ybbase.framework.model.po.system.*;
import com.ybbase.framework.service.system.LogService;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.service.system.RoleService;
import com.ybbase.framework.service.system.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户表 前端控制器
 *
 * @author cg
 * @since 2019-11-26
 * 云平台2.0
 */
@RestController
@RequestMapping(value = "/user", produces = {"application/json;charset=UTF-8"})
@Api("系统用户表")
public class UserController extends BaseController {

    private static final Logger LOGGER = LogManager.getLogger(UserController.class);

    @Autowired
    private UserService targetService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private LogService logService;
    @Autowired
    private OrganizationService organizationService;


    /**
     * 系统用户表分页查询
     *
     * @param pageIndex 页数
     * @param step      每页数量
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/list")
    @ApiOperation(value = "系统用户表分页查询", notes = "系统用户表分页查询", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "user", value = "系统用户表", dataType = "User对象")
    })
    public ResponseBean findListByPage(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, User user) {
        try {
            Page<User> page = new Page(pageIndex, step);
            if (user.getName() != null) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(User::getName, user.getName());
                targetService.page(page, queryWrapper);
            } else {
                Wrapper<User> wrapper = new QueryWrapper<User>();
                targetService.page(page, wrapper);
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统用户表分页" + CommonResultCode.SUCCESS.getMsg(), getRole(page));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统用户表分页查询异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统用户表分页" + CommonResultCode.FAIL.getMsg());
        }
    }


    /**
     * 系统用户表获取全部数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/all")
    @ApiOperation(value = "系统用户表获取全部数据", notes = "系统用户表获取全部数据")
    public ResponseBean findAll() {
        try {
            List<User> models = targetService.list();
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统用户表获取全部数据" + CommonResultCode.SUCCESS.getMsg(), models);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统用户表获取全部数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统用户表获取全部数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统用户表根据ID查找数据
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/find")
    @ApiOperation(value = "系统用户表根据ID查找数据", notes = "系统用户表根据ID查找数据")
    @ApiImplicitParam(required = true, name = "id", value = "唯一编码", dataType = "Long")
    public ResponseBean find(@RequestParam("id") Long id) {
        try {
            User user = targetService.getById(id);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统用户表根据ID查找数据" + CommonResultCode.SUCCESS.getMsg(), user);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统用户表根据ID查找数据异常:{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统用户表根据ID查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统用户表保存数据
     * 未修改
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @PostMapping("/save")
    @ApiOperation(value = "系统用户表保存数据", notes = "系统用户表保存数据")
    @ApiImplicitParam(required = true, name = "user", value = "系统用户表", dataType = "User对象")
    public ResponseBean save(@RequestBody User user) {
        try {
            String logName;
            if (user.getLoginName() != null && (user.getId() == null || user.getId() == 0)) {
                logName = user.getLoginName();
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                User user1 = targetService.getOne(queryWrapper.lambda().eq(User::getLoginName, logName));
                if (user1 != null) {
                    return new ResponseBean(CommonResultCode.FAIL.getCode(), "该登录名已经存在添加" + CommonResultCode.FAIL.getMsg(), user);
                }
            }
            user.setPassword(DESUtil.encryptBasedDes("111111"));
            String msg = "";
            if (user.getId() == null || user.getId() == 0) {
                msg = "，初始密码111111。";
            }
            targetService.saveUser(user);
            logService.saveLog(LogType.add.getEnumKey(), LogFunType.user.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统用户表保存数据" + CommonResultCode.SUCCESS.getMsg() + msg);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统用户表保存数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统用户表保存数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统用户表更新数据
     *
     * @param request 系统用户表
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @PostMapping("/update")
    @ApiOperation(value = "系统用户表更新数据", notes = "系统用户表更新数据")
    @ApiImplicitParam(required = true, name = "user", value = "系统用户表", dataType = "User对象")
    public ResponseBean update(HttpServletRequest request) {
        try {
            BeanUtil beanUtil = new BeanUtil();
            User user = (User) beanUtil.mapToObject(request.getParameterMap(), User.class);
            targetService.updateById(user);
            logService.saveLog(LogType.edit.getEnumKey(), LogFunType.user.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统用户表更新数据" + CommonResultCode.SUCCESS.getMsg(), user);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统用户表更新数据:{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统用户表更新数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统用户表更新数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/updatePassWord")
    @ApiOperation(value = "系统用户表更新数据", notes = "系统用户表更新数据")
    @ApiImplicitParam(required = true, name = "user", value = "系统用户表", dataType = "User对象")
    public ResponseBean updatePassWord(@RequestParam String id, @RequestParam String oldPassword, @RequestParam String password) {
        try {
            User user = targetService.getById(id);
            if (!user.getPassword().equals(DESUtil.encryptBasedDes(oldPassword))) {
                return new ResponseBean(CommonResultCode.FAIL.getCode(), "输入原密码错误" + CommonResultCode.FAIL.getMsg());
            }
            user.setPassword(DESUtil.encryptBasedDes(password));
            targetService.updateById(user);
            logService.saveLog(LogType.password.getEnumKey(), LogFunType.user.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "密码修改" + CommonResultCode.SUCCESS.getMsg(), user);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("密码修改:{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "密码修改" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 密码重置
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/resetPassWord")
    @ApiOperation(value = "密码重置", notes = "密码重置")
    @ApiImplicitParam(required = true, name = "user", value = "系统用户表", dataType = "User对象")
    public ResponseBean resetPassWord(@RequestParam String id) {
        try {
            User user = targetService.getById(Integer.parseInt(id));
            user.setPassword(DESUtil.encryptBasedDes("111111"));
            targetService.updateById(user);
            logService.saveLog(LogType.password.getEnumKey(), LogFunType.user.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "密码重置为111111", user);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("密码重置:{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "密码重置" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统用户表删除数据
     *
     * @param ids 批量删除数据
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @GetMapping("/del")
    @ApiOperation(value = "系统用户表删除数据", notes = "系统用户表删除数据")
    @ApiImplicitParam(required = true, name = "ids", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean del(@RequestParam("ids") String ids) {
        try {
            String[] ss = ids.split(",");
            for (int i = 0; i < ss.length; i++) {
                User user = targetService.getById(ss[i]);
                if (user != null && user.getIsAdmin() != 1) {
                    targetService.removeById(ss[i]);
                } else {
                    return new ResponseBean(CommonResultCode.FAIL.getCode(), "超级管理员不能删除！");
                }
            }
            logService.saveLog(LogType.del.getEnumKey(), LogFunType.user.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统用户表删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统用户表删除数据:{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统用户表删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据用户编码获取到用户的全部信息
     *
     * @param userId 用户编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-28 16:53
     * @since cloud2.0
     */
    @GetMapping("/getUserAllInfo")
    @ApiOperation(value = "根据用户编码获取到用户的全部信息", notes = "根据用户编码获取到用户的全部信息")
    @ApiImplicitParam(required = true, name = "userId", value = "用户编码", dataType = "Integer")
    public ResponseBean getUserAllInfo(@RequestParam Integer userId) {
        try {
            User user = targetService.getUserAllInfo(userId);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "根据用户编码获取到用户的全部信息" + CommonResultCode.SUCCESS.getMsg(), user);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("根据用户编码获取到用户的全部信息：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据用户编码获取到用户的全部信息" + CommonResultCode.FAIL.getMsg());
        }
    }

    ///**
    // * 保存用户组织机构
    // *
    // * @param organUser 用户角色信息
    // * @author cg
    // * @date 2019-11-28 10:47
    // * @since cloud2.0
    // */
    //@PostMapping("/saveUserOrgan")
    //@ApiOperation(value = "保存用户组织机构", notes = "保存用户组织机构")
    //@ApiImplicitParam(required = true, name = "organUser", value = "用户机构信息", dataType = "OrganUser对象")
    //public ResponseBean saveUserOrgan(@RequestBody OrganUser organUser) {
    //    try {
    //        List<OrganUser> list = targetService.getOrganUserList(organUser.getUserId(), organUser.getOrgId());
    //        if (list != null && list.size() > 0) {
    //            return new ResponseBean(CommonResultCode.FAIL.getCode(), "保存用户组织机构信息" + CommonResultCode.FAIL.getMsg());
    //        }
    //        targetService.saveUserOrgan(organUser);
    //        return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "保存用户组织机构信息" + CommonResultCode.SUCCESS.getMsg());
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //        LOGGER.error("保存用户组织机构信息：{}", e.getMessage());
    //        return new ResponseBean(CommonResultCode.FAIL.getCode(), "保存用户组织机构信息" + CommonResultCode.FAIL.getMsg());
    //    }
    //}

    /**
     * 删除用户的组织机构关联
     *
     * @param organUser 用户角色信息
     * @return ResponseBean
     * @author cg
     * @date 2019-11-26
     * @since cloud2.0
     */
    @DeleteMapping("/deleteUserOrgan")
    @ApiOperation(value = "删除用户的组织机构关联", notes = "删除用户的组织机构关联")
    @ApiImplicitParam(required = true, name = "organUser", value = "用户机构信息", dataType = "OrganUser对象")
    public ResponseBean deleteUserOrgan(OrganUser organUser) {
        try {
            targetService.deleteUserOrgan(organUser.getUserId(), organUser.getOrgId());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "删除用户的组织机构关联" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除用户的组织机构关联：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "删除用户的组织机构关联" + CommonResultCode.FAIL.getMsg());
        }
    }

    private Page<User> getRole(Page<User> page) {
        List<User> users = page.getRecords();
        for (User user : users) {
            String roleNames = "";
            String defaultOrganNames = "";
            List<Role> list = roleService.getRoleListByUserId(user.getId());
            if (list != null && !list.isEmpty()) {
                for (Role r : list) {
                    roleNames = roleNames + "|" + r.getName();
                }
            }
            user.setRoleNames(roleNames);
            List<Organization> organizationList = organizationService.getOrgListByUserId(user.getId());
            if (organizationList != null && !organizationList.isEmpty()) {
                for (Organization o : organizationList) {
                    defaultOrganNames = defaultOrganNames + "|" + o.getName();
                }
            }
            user.setDefaultOrgName(defaultOrganNames);
        }
        page.setRecords(users);
        return page;
    }

    /**
     * 根据机构获取用户数据
     *
     * @param
     * @return
     * @author cg
     * @date 2020-01-11 12:04
     * @since cloud2.0
     */
    @GetMapping("/getUListByOrgId")
    public ResponseBean getUListByOrgId(String organId) {
        try {
            List<User> users = targetService.getUserListByOrgId(organId);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "根据机构获取用户数据" + CommonResultCode.SUCCESS.getMsg(), users);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("根据机构获取用户数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据机构获取用户数据" + CommonResultCode.FAIL.getMsg(), new ArrayList<>());
        }
    }

    /**
     * 根据角色ID获取下面所有的用户
     *
     * @param pageIndex
     * @param step
     * @param id
     * @return
     * @date 2020年3月2日12:23:10
     * @author phm
     */
    @GetMapping("/getUserByRoleId")
    public ResponseBean getUserByRoleId(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                        @RequestParam(name = "size", defaultValue = "20") int step, Integer role_id, String name) {
        try {
            Page<User> page = new Page(pageIndex, step);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            List<Integer> list = roleService.findUserId(role_id);
            Integer[] id = list.toArray(new Integer[list.size()]);
            targetService.getUserByRoleId(page, queryWrapper, id, name);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "根据角色ID获取下面所有的用户" + CommonResultCode.SUCCESS.getMsg(), getRole(page));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("根据角色ID获取下面所有的用户异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据角色ID获取下面所有的用户" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据用户ID获取相关数据
     * @param
     * @return
     * @author cg
     * @date 2020-03-29 17:58
     * @since cloud2.0
     */
    @GetMapping("/getScopeById")
    public ResponseBean getScopeById(@RequestParam(value = "userId") int userId){
        try {
            User user = targetService.getScopeById(userId);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "根据角色ID获取下面所有的用户" + CommonResultCode.SUCCESS.getMsg(),user);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("根据角色ID获取下面所有的用户异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据角色ID获取下面所有的用户" + CommonResultCode.FAIL.getMsg());
        }

    }
}
